import { login, logout, getInfo } from '@/api/login'
import {getToken, setToken, removeToken, setSystem} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
      //浏览器中将 Vuex 的 state 持久化到 localStorage,解决页面刷新后 Vuex 的值被清空
      realName:localStorage.getItem('realName') || '', // 初始化时从 localStorage 恢复,//存储用户姓名
      curSysAcc:'',//当前进入的系统
      curSysAccId:localStorage.getItem('curSysAccId') || '', // 初始化时从 localStorage 恢复,//存储用户姓名
      curSysAccName:localStorage.getItem('curSysAccName') || '',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
      SET_REAL_NAME: (state, realName) => { //定义一个 mutation 用于更新 realName
          state.realName = realName
          //浏览器中将 Vuex 的 state 持久化到 localStorage,解决页面刷新后 Vuex 的值被清空
          localStorage.setItem('realName', realName); // 每次修改时同步到 localStorage
      },
      SET_CUR_SYSACC: (state, curSysAcc) => { //定义一个 mutation 用于更新 curSysAcc
          state.curSysAcc = curSysAcc

          state.curSysAccId = curSysAcc.pkId
          state.curSysAccName= curSysAcc.funcName
          localStorage.setItem('curSysAccId', curSysAcc.pkId); // 每次修改时同步到 localStorage
          localStorage.setItem('curSysAccName', curSysAcc.funcName);
      },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
            let token=res.data.accessToken;
            //let systemKye=res.data.systemKey;
            //setSystem(systemKye)
          setToken(token)
          commit('SET_TOKEN', token)
            commit('SET_REAL_NAME', res.data.realName);
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {//renshuai
          const user = res.data.user
          const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : /*process.env.VUE_APP_BASE_API + */user.avatar;
          if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.data.roles)
            //commit('SET_PERMISSIONS', res.data.permissions) //renshuai：移到单独if判断
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }

          if (res.data.permissions && res.data.permissions.length > 0) {//renshuai
              commit('SET_PERMISSIONS', res.data.permissions)
          }

          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

      //更新当前系统
      UpdateCurSys({ commit,state ,dispatch }, curSysAcc) {
        debugger;
        if(curSysAcc.pkId != state.curSysAcc.pkId){
            commit('SET_CUR_SYSACC', curSysAcc);
            //重置角色信息，在 src/permission.js 的 router.beforeEach 通过 store.getters.roles.length === 0 来更新用户信息和路由
            //有可能是切换系统操作，切换时 需要重新查询角色和路由
            commit('SET_ROLES', [])

            // 调用其他模块的 action
            // dispatch('模块名/方法名', payload, { root: true });
            // 第三个参数 { root: true } 表示从全局调用，而非当前模块的 action
            //第二个参数 payload 是传递给目标 action 的参数，代表了 action 执行时需要的附加数据。你可以通过 payload 向目标 action
            dispatch('tagsView/delAllViews', null, { root: true }); // 使用 root:true//关闭所有页签
        }

      },
  }
}

export default user
